﻿using System;
using System.Data.OleDb;
using System.Net;
using System.Windows.Forms;
using System.Configuration;
using System.IO;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Diagnostics;

namespace accessSyncTools
{
    public partial class SyncBangD : Form
    {
        Configuration config;
        OleDbConnection conn;
        Stopwatch stopWatch;

        string serverUrl = "";

        public SyncBangD()
        {
            InitializeComponent();
        }

        string obj2Json(Object obj)
        {
            return JsonConvert.SerializeObject(obj);
        }

        object json2Obj(string json)
        {
            return JsonConvert.DeserializeObject<object>(json);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.sync_all();
        }
        
        string CreateConfig()
        {
            try
            {
                string configFile = AppDomain.CurrentDomain.BaseDirectory + @"app.config";
                //if (!File.Exists(configFile))
                //{
                //    string xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n<configuration>\r\n<appSettings>\r\n<add key=\"bangfbh\" value=\"1\"/>\r\n</appSettings>\r\n</configuration>";
                //    using (StreamWriter sw = new StreamWriter(configFile))
                //    {
                //        sw.Write(xml);
                //    }
                //}
                return configFile;
            }
            catch (Exception ex)
            {
                string msg = ex.Message;
                throw;
            }
        }

        string getItem(string item)
        {
            if (this.config.AppSettings.Settings[item] == null)
            {
                return string.Empty;
            }
            else
            {
                return this.config.AppSettings.Settings[item].Value;
            }
        }

        String bangFBH = "";


        private void Form1_Load(object sender, EventArgs e)
        {
            string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Environment.CurrentDirectory + @"\chengzhongku.mdb";
            conn = new OleDbConnection(connectionString);
            try
            {
                conn.Open();

            } catch(Exception error) {
                MessageBox.Show(error.Message);
                Application.Exit();
                return;
            }

            ExeConfigurationFileMap ecf = new ExeConfigurationFileMap();
            ecf.ExeConfigFilename = this.CreateConfig();
            this.config = ConfigurationManager.OpenMappedExeConfiguration(ecf, ConfigurationUserLevel.None);
            this.bangFBH = this.getItem("bangfbh");
            this.serverUrl = this.getItem("serverUrl");

            //if(this.bangFBH.Equals(""))
            //{
            //    MessageBox.Show("读取磅房编号失败，请删除配置文件后再次运行程序。生产新的配置文件");
            //    Application.Exit();
            //    return;
            //}

            textBox1.Text += "磅房编号: " + this.bangFBH + "\r\n";
            textBox1.Text += "服务器地址: " + this.serverUrl + "\r\n\r\n";

            OleDbCommand cmd = conn.CreateCommand();
            cmd.CommandText = "select count(*) from chengzhong";
            
            textBox1.Text += "本地数据库中共计: " + cmd.ExecuteScalar() + " 条磅单\r\n\r\n";
        }

        private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            object a = e.Argument;//获取RunWorkerAsync(object argument)传入的值
            BackgroundWorker worker = sender as BackgroundWorker;

            OleDbCommand cmd = conn.CreateCommand();
            cmd.CommandText = "select count(*) from chengzhong where createTime between #" + dateTimePicker1.Text + 
                " 00:00:00# and #" + dateTimePicker2.Text + " 23:59:59#";
            if(cmd.ExecuteScalar().Equals(0))
            {
                worker.ReportProgress(-1, "查询到0条记录...\r\n\r\n");
                return;
            }
                
            string sql = "select * from chengzhong where createTime between #" + dateTimePicker1.Text + " 00:00:00# and #" + dateTimePicker2.Text + " 23:59:59#";
            Console.WriteLine(sql);
            cmd.CommandText = sql;
            OleDbDataReader dr = cmd.ExecuteReader();

            List<BangD> list = new List<BangD>();
            int count = 0;
            while (dr.Read())
            {
                BangD bangD = new BangD();
                bangD.czdanwei = dr["czdanwei"] + "";
                bangD.czpinming = dr["czpinming"] + "";
                bangD.czxinghao = dr["czxinghao"] + "";
                bangD.czchehao = dr["czchehao"] + "";
                bangD.czmaozhong = dr["czmaozhong"] + "";
                bangD.czpizhong = dr["czpizhong"] + "";
                bangD.czjingzhong = dr["czjingzhong"] + "";
                bangD.czrenyuan = dr["czrenyuan"] + "";
                bangD.czfangshi = dr["czfangshi"] + "";
                bangD.czriqi = dr["czriqi"] + "";
                bangD.czbianhao = dr["czbianhao"] + "";
                bangD.czcunshijian = dr["czcunshijian"] + "";
                bangD.czbangf = this.bangFBH;
                bangD.czcrku = dr["czcrku"] + "";
                
                bangD.createTime = dr["createTime"] + "";
                bangD.createTime = bangD.createTime.Replace("/", "-");

                bangD.yunsgsName = dr["yunsgsName"] + "";
                bangD.remarks = dr["remarks"] + "";

                bangD.updateTime = dr["updateTime"] + "";
                bangD.updateTime = bangD.updateTime.Replace("/", "-");

                list.Add(bangD);

                count++;
            }

            //textBox1.Text += "准备同步: " + count + " 条记录\r\n\r\n";
            worker.ReportProgress(1, "查询到: " + count + " 条记录\r\n\r\n同步中... 请稍后！\r\n\r\n");
            

            string json = obj2Json(list);
            Console.WriteLine(json);

            worker.ReportProgress(50, serverUrl + "/bangd/czBangd/receiveCaijiData?bangfCode=" + this.bangFBH);
            string rtn = httpPost(serverUrl + "/bangd/czBangd/receiveCaijiData?bangfCode=" + this.bangFBH, json);
            
            worker.ReportProgress(99, rtn);

        }

        private string httpPost(string url, string json)
        {
            //textBox1.Text += url + "\r\n";
            byte[] bs = Encoding.UTF8.GetBytes(json);

            HttpWebRequest httpWebRequest = WebRequest.Create(url) as HttpWebRequest;

            httpWebRequest.Method = "POST";
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.ContentLength = bs.Length;

            try
            {
                using (Stream reqStream = httpWebRequest.GetRequestStream())
                {
                    reqStream.Write(bs, 0, bs.Length);
                }

                using (WebResponse wr = httpWebRequest.GetResponse())
                {
                    using (var responseStream = wr.GetResponseStream())
                    {
                        byte[] readBuffer = new byte[1000];
                        List<byte> allData = new List<byte>();
                        int readBytes;

                        do
                        {
                            readBytes = responseStream.Read(readBuffer, 0, readBuffer.Length);

                            for (var i = 0; i < readBytes; i++)
                            {
                                allData.Add(readBuffer[i]);
                            }

                        } while (readBytes > 0);//如果readBytes为0表示HttpWebResponse中的所有数据已经被读取完毕

                        string message = Encoding.UTF8.GetString(allData.ToArray());
                        //textBox1.Text += message + "\r\n\r\n";
                        //worker.ReportProgress(99, message + "\r\n");
                        return message + "\r\n\r\n";

                    }
                }

            }
            catch (Exception error)
            {
                //MessageBox.Show(error.Message);
                //worker.ReportProgress(50, "异常, " + error.Message + "\r\n");
                //textBox1.Text += "异常, " + error.Message + "\r\n";
                return "异常, " + error.Message + " 请检查网络！\r\n";

            }
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            textBox1.Text += "处理完成\r\n";
            button1.Enabled = true;

            stopWatch.Stop();
            TimeSpan timespan = stopWatch.Elapsed; //  获取当前实例测量得出的总时间
            double hours = timespan.TotalHours; // 总小时
            double minutes = timespan.TotalMinutes;  // 总分钟
            double seconds = timespan.TotalSeconds;  //  总秒数
            double milliseconds = timespan.TotalMilliseconds;  //  总毫秒数

            textBox1.Text += "运行耗时: " + timespan.TotalSeconds + " 秒\r\n\r\n";
        }

        private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
        {
            textBox1.Text += (string)e.UserState;
        }

        // 同步运输车辆
        void sync_chehao()
        {
            OleDbCommand cmd = conn.CreateCommand();
            string sql = "SELECT DISTINCT czchehao FROM chengzhong";
            cmd.CommandText = sql;
            OleDbDataReader dr = cmd.ExecuteReader();

            List<string> list = new List<string>();
            int count = 0;
            while (dr.Read())
            {
                list.Add(dr["czchehao"] + "");
                count++;
            }

            textBox1.Text += "本地数据库查询到，" + count + " 个车牌号\r\n开始同步...\r\n";

            string json = obj2Json(list);
            Console.WriteLine(json);

            string rtn = httpPost(serverUrl + "/bangd/czBangd/receiveChepNum?bangfCode=" + this.bangFBH, json);
            textBox1.Text += rtn;
            
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            textBox1.SelectionStart = textBox1.Text.Length; //Set the current caret position at the end
            textBox1.ScrollToCaret(); //Now scroll it automatically
        }

        // 同步物料
        void sync_wul()
        {
            OleDbCommand cmd = conn.CreateCommand();
            string sql = "SELECT DISTINCT czpinming FROM chengzhong";
            cmd.CommandText = sql;
            OleDbDataReader dr = cmd.ExecuteReader();

            List<string> list = new List<string>();
            int count = 0;
            while (dr.Read())
            {
                list.Add(dr["czpinming"] + "");
                count++;
            }

            textBox1.Text += "本地数据库查询到，" + count + " 个物料名称\r\n开始同步...\r\n";

            string json = obj2Json(list);
            Console.WriteLine(json);

            string rtn = httpPost(serverUrl + "/bangd/czBangd/receiveWul?bangfCode=" + this.bangFBH, json);
            textBox1.Text += rtn;
        }

        void sync_guig()
        {
            OleDbCommand cmd = conn.CreateCommand();
            string sql = "SELECT DISTINCT czxinghao FROM chengzhong";
            cmd.CommandText = sql;
            OleDbDataReader dr = cmd.ExecuteReader();

            List<string> list = new List<string>();
            int count = 0;
            while (dr.Read())
            {
                list.Add(dr["czxinghao"] + "");
                count++;
            }

            textBox1.Text += "本地数据库查询到，" + count + " 个规格名称\r\n开始同步...\r\n";

            string json = obj2Json(list);
            Console.WriteLine(json);

            string rtn = httpPost(serverUrl + "/bangd/czBangd/receiveGuig?bangfCode=" + this.bangFBH, json);
            textBox1.Text += rtn;
        }

        // 同步物料公司
        void sync_wulgs()
        {
            OleDbCommand cmd = conn.CreateCommand();
            string sql = "SELECT DISTINCT czdanwei FROM chengzhong";
            cmd.CommandText = sql;
            OleDbDataReader dr = cmd.ExecuteReader();

            List<string> list = new List<string>();
            int count = 0;
            while (dr.Read())
            {
                list.Add(dr["czdanwei"] + "");
                count++;
            }

            textBox1.Text += "本地数据库查询到，" + count + " 个供应商名称\r\n开始同步...\r\n";

            string json = obj2Json(list);
            Console.WriteLine(json);

            string rtn = httpPost(serverUrl + "/bangd/czBangd/receiveSupplier?bangfCode=" + this.bangFBH, json);
            textBox1.Text += rtn;

        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            textBox1.Text += "定时同步，每小时同步一次、人\r\n";
            this.sync_all();
        }

        void sync_all()
        {
            textBox1.Text += DateTime.Now + "\r\n";

            stopWatch = new Stopwatch();
            stopWatch.Start();

            //this.sync_wulgs();
            //this.sync_wul();
            //this.sync_guig();
            //this.sync_chehao();

            backgroundWorker1.RunWorkerAsync();
            
            textBox1.Text += "开始同步磅单，时间范围 " + dateTimePicker1.Text + " 00:00:00 ~ " + dateTimePicker2.Text + " 23:59:59\r\n";
            button1.Enabled = false;
        }
    }
}

